import { nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { Ref } from 'vue'

// 语音指令处理结果接口
export interface VoiceCommandResult {
  commandDetected: boolean
  commandType?: 'send' | 'close_mic' | 'clear_content' | 'clear_screen' | 'confirm_interaction' | 'cancel_interaction'
  processedText?: string
  shouldExecuteAction?: boolean
  action?: () => Promise<void> | void
}

// 语音指令处理器配置接口
export interface VoiceCommandHandlerConfig {
  inputText: Ref<string>
  currentRecognitionText: Ref<string>
  sendMessage: () => Promise<void>
  stopRecording: () => Promise<void>
  clearScreen: () => void
  respondToInteraction?: (approved: boolean) => Promise<void>
  isInInteractionMode?: Ref<boolean>
}

// 语音指令处理器类
export class VoiceCommandHandler {
  private config: VoiceCommandHandlerConfig

  constructor(config: VoiceCommandHandlerConfig) {
    this.config = config
  }

  /**
   * 处理语音识别结果中的指令
   * @param recognitionText 语音识别的文本
   * @param isFinal 是否为最终识别结果
   * @returns 处理结果
   */
  processVoiceCommand(recognitionText: string, isFinal: boolean): VoiceCommandResult {
    console.log('处理语音指令:', recognitionText, 'isFinal:', isFinal)

    // 只有当识别完成时才检测指令（避免实时识别中的误触发）
    if (!isFinal) {
      return {
        commandDetected: false
      }
    }

    // 去除末尾的标点符号和空格
    const cleanText = recognitionText.trim().replace(/[。！？.,!?]*$/, '')
    
    // 检测发送指令 - 以"发送"结尾
    if (cleanText.endsWith('发送')) {
      return this.handleSendCommand(recognitionText, isFinal)
    }
    
    // 检测关闭麦克风指令 - 以"关闭麦克风"结尾
    if (cleanText.endsWith('关闭麦克风')) {
      return this.handleCloseMicCommand(recognitionText, isFinal)
    }
    
    // 检测清空内容指令 - 以"清空"或"清除"结尾
    if (cleanText.endsWith('清空') || cleanText.endsWith('清除')|| cleanText.endsWith('重录')) {
      return this.handleClearContentCommand(recognitionText, isFinal)
    }
    
    // 检测清屏指令 - 以"清屏"结尾
    if (cleanText.endsWith('清屏')) {
      return this.handleClearScreenCommand(recognitionText, isFinal)
    }

    // 检测执行指令 - 以"执行"或"确认"结尾 (仅在人机交互模式下有效)
    if (this.config.isInInteractionMode?.value && (cleanText.endsWith('执行') || cleanText.endsWith('确认'))) {
      return this.handleConfirmInteractionCommand(recognitionText, isFinal)
    }
    
    // 检测取消指令 - 以"取消"结尾 (仅在人机交互模式下有效)
    if (this.config.isInInteractionMode?.value && cleanText.endsWith('取消')) {
      return this.handleCancelInteractionCommand(recognitionText, isFinal)
    }

    // 没有检测到指令
    return {
      commandDetected: false
    }
  }

  /**
   * 处理发送指令
   */
  private handleSendCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"发送"关键词:', text)

    // 去掉"发送"，只保留"发送"前面的内容
    const currentText = text.replace(/发送[。！？.,!?]*$/g, '').trim()
    
    // 将当前识别的内容（去掉发送）添加到输入框中
    if (currentText) {
      if (this.config.inputText.value) {
        this.config.inputText.value += ' ' + currentText
      } else {
        this.config.inputText.value = currentText
      }
    }
    
    // 检查输入框是否有内容要发送
    if (this.config.inputText.value.trim()) {
      this.config.currentRecognitionText.value = ''
      
      ElMessage.success({
        message: `✅ 检测到发送指令，自动发送: "${this.config.inputText.value}"`,
        duration: 2000
      })
      
      return {
        commandDetected: true,
        commandType: 'send',
        processedText: currentText,
        shouldExecuteAction: true,
        action: async () => {
          // 延迟一点发送，确保输入框更新
          await nextTick()
          await this.config.sendMessage()
        }
      }
    } else {
      ElMessage.warning('⚠️ 检测到发送指令，但没有要发送的内容')
      this.config.currentRecognitionText.value = ''
      
      return {
        commandDetected: true,
        commandType: 'send',
        shouldExecuteAction: false
      }
    }
  }

  /**
   * 处理关闭麦克风指令
   */
  private handleCloseMicCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"关闭麦克风"关键词:', text)

    // 去掉"关闭麦克风"，保留前面的内容
    const currentText = text.replace(/关闭麦克风[。！？.,!?]*$/g, '').trim()
    
    // 如果有前面的内容，添加到输入框中
    if (currentText) {
      if (this.config.inputText.value) {
        this.config.inputText.value += ' ' + currentText
      } else {
        this.config.inputText.value = currentText
      }
    }
    
    this.config.currentRecognitionText.value = ''
    
    ElMessage.success({
      message: '🎤 检测到关闭麦克风指令，正在关闭...',
      duration: 2000
    })
    
    return {
      commandDetected: true,
      commandType: 'close_mic',
      processedText: currentText,
      shouldExecuteAction: true,
      action: async () => {
        // 延迟一点关闭麦克风，确保消息显示
        await nextTick()
        await this.config.stopRecording()
      }
    }
  }

  /**
   * 处理清空内容指令
   */
  private handleClearContentCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"清空内容"关键词:', text)
    console.log('isFinal:', isFinal)

    // 清空输入框内容
    this.config.inputText.value = ''
    this.config.currentRecognitionText.value = ''
    
    ElMessage.success({
      message: '🗑️ 检测到清空指令，已清空输入内容',
      duration: 2000
    })
    
    return {
      commandDetected: true,
      commandType: 'clear_content',
      shouldExecuteAction: true
    }
  }

  /**
   * 处理清屏指令
   */
  private handleClearScreenCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"清屏"关键词:', text)

    // 清空对话记录
    this.config.clearScreen()
    this.config.currentRecognitionText.value = ''
    
    ElMessage.success({
      message: '🧹 检测到清屏指令，已清空对话记录',
      duration: 2000
    })
    
    return {
      commandDetected: true,
      commandType: 'clear_screen',
      shouldExecuteAction: true
    }
  }

  /**
   * 处理确认执行指令
   */
  private handleConfirmInteractionCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"确认执行"关键词:', text)

    if (!this.config.respondToInteraction) {
      ElMessage.warning('⚠️ 当前没有可确认的操作')
      return {
        commandDetected: true,
        commandType: 'confirm_interaction',
        shouldExecuteAction: false
      }
    }

    // 去掉"执行"或"确认"，保留前面的内容作为补充说明
    const currentText = text.replace(/(执行|确认)[。！？.,!?]*$/g, '').trim()
    
    // 如果有前面的内容，添加到输入框中作为补充说明
    if (currentText) {
      if (this.config.inputText.value) {
        this.config.inputText.value += ' ' + currentText
      } else {
        this.config.inputText.value = currentText
      }
    }
    
    this.config.currentRecognitionText.value = ''
    
    ElMessage.success({
      message: '✅ 检测到确认执行指令，正在执行操作...',
      duration: 2000
    })
    
    return {
      commandDetected: true,
      commandType: 'confirm_interaction',
      processedText: currentText,
      shouldExecuteAction: true,
      action: async () => {
        // 延迟一点执行，确保输入框更新
        await nextTick()
        await this.config.respondToInteraction!(true)
      }
    }
  }

  /**
   * 处理取消指令
   */
  private handleCancelInteractionCommand(text: string, isFinal: boolean): VoiceCommandResult {
    console.log('检测到"取消"关键词:', text)

    if (!this.config.respondToInteraction) {
      ElMessage.warning('⚠️ 当前没有可取消的操作')
      return {
        commandDetected: true,
        commandType: 'cancel_interaction',
        shouldExecuteAction: false
      }
    }

    // 去掉"取消"，保留前面的内容作为补充说明
    const currentText = text.replace(/取消[。！？.,!?]*$/g, '').trim()
    
    // 如果有前面的内容，添加到输入框中作为补充说明
    if (currentText) {
      if (this.config.inputText.value) {
        this.config.inputText.value += ' ' + currentText
      } else {
        this.config.inputText.value = currentText
      }
    }
    
    this.config.currentRecognitionText.value = ''
    
    ElMessage.info({
      message: '❌ 检测到取消指令，正在取消操作...',
      duration: 2000
    })
    
    return {
      commandDetected: true,
      commandType: 'cancel_interaction',
      processedText: currentText,
      shouldExecuteAction: true,
      action: async () => {
        // 延迟一点执行，确保输入框更新
        await nextTick()
        await this.config.respondToInteraction!(false)
      }
    }
  }
}

// 默认导出语音指令处理器类
export default VoiceCommandHandler 